25.7 异步闭包
一句话记住
普通闭包是“一张随身带的小纸条,上面写着要做的事”。异步闭包 async |参数| { … } 是“每次照着做都会给你一张取餐小票(Future)的小纸条”。它自 Rust 1.85 起稳定,所有 Edition 都能用。
本节接着 25.5 往下讲,需要你已经知道:async fn 调用后得到 Future,要 .await 才会执行;闭包能“捕获”外面的变量(第 22 章)。全部示例只用标准库,可在稳定版 1.100.1 直接运行。
25.7.1 长什么样
在闭包前面加 async:
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
// 教学用最简执行器(讲解见 25.5)
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
}
}
fn main() {
let bonus = 10;
// 异步闭包:捕获了外面的 bonus
let add_bonus = async |score: i32| score + bonus;
let ticket = add_bonus(5); // 调用:只得到小票,还没算
assert_eq!(block_on(ticket), 15); // 等小票:这时才算
assert_eq!(block_on(add_bonus(7)), 17); // 可以反复调用
}对照三种写法:
| 写法 | 调用它得到什么 | 能捕获外部变量吗 |
|---|---|---|
async fn f(x: i32) -> i32 { … } | 一个 Future | 不能(它是函数) |
|x: i32| x + 1(普通闭包) | 直接得到结果 | 能 |
async |x: i32| x + 1(异步闭包) | 一个 Future | 能 |
和普通闭包一样,也可以写 async move |x| { … },把捕获的变量整个搬进闭包里。
25.7.2 把异步闭包当参数:AsyncFn 三兄弟
普通闭包有 Fn / FnMut / FnOnce 三个 trait(见 22.3)。异步闭包有一一对应的三兄弟,它们和异步闭包一起在 1.85 稳定,并且已经在 prelude 里,不用 use:
| trait | 能调用几次 | 调用时怎么用捕获的变量 | 对应的普通闭包 trait |
|---|---|---|---|
AsyncFn | 很多次,可以同时进行 | 只读地借用 | Fn |
AsyncFnMut | 很多次,一次接一次 | 可以修改 | FnMut |
AsyncFnOnce | 只能一次 | 可以把东西拿走 | FnOnce |
写法也和 Fn 一样,括号里是参数,箭头后面是 .await 之后得到的类型(不用写 Future):
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
}
}
// 接受“给一个 i32、异步地还一个 i32”的任何东西
async fn apply_twice(f: impl AsyncFn(i32) -> i32, start: i32) -> i32 {
let once = f(start).await;
f(once).await
}
async fn double(x: i32) -> i32 {
x * 2
}
fn main() {
// 1. 传异步闭包
assert_eq!(block_on(apply_twice(async |x| x + 1, 5)), 7);
// 2. 传 async fn:它也实现了 AsyncFn
assert_eq!(block_on(apply_twice(double, 5)), 20);
// 3. 传“返回 async 块的普通闭包”:同样满足 AsyncFn
assert_eq!(block_on(apply_twice(|x| async move { x - 1 }, 5)), 3);
}所以写接收方(函数参数)时,优先用 AsyncFn*:三种调用方都能接受。
25.7.3 为什么需要它:async || {} 和 || async {} 的区别
在 1.85 以前,人们用“返回 async 块的普通闭包” || async { … } 来代替。它在简单情况下够用,但有一件事做不到:让返回的 Future 借用闭包自己捕获的东西。
看一个具体任务:把收到的每条消息记到外面的 log 里。
旧写法——普通闭包返回 async 块:
use std::future::Future;
async fn for_each_message<F, Fut>(mut f: F)
where
F: FnMut(&str) -> Fut,
Fut: Future<Output = ()>,
{
f("你好").await;
f("再见").await;
}
fn main() {
let mut log: Vec<String> = Vec::new();
// 错误:async 块想把闭包捕获的 &mut log 带到闭包外面去
let _future = for_each_message(|message: &str| async {
log.push(message.to_string());
});
}预期报错:error: captured variable cannot escape `FnMut` closure body(同时还有一条 lifetime may not live long enough)。编译器的解释是:FnMut 闭包只在被调用的那一刻能用它捕获的变量,不能把指向这些变量的引用交到外面去;而 async { … } 块恰恰是一个要“带出去、以后再执行”的东西。参数 message: &str 也有同样的麻烦:Fut 是一个固定的类型,没法表达“每次调用借的时间都不一样”。
新写法——异步闭包配 AsyncFnMut:
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
}
}
async fn for_each_message(mut f: impl AsyncFnMut(&str)) {
f("你好").await;
f("再见").await;
}
fn main() {
let mut log: Vec<String> = Vec::new();
block_on(for_each_message(async |message: &str| {
log.push(message.to_string()); // 可以修改捕获的 log,也可以借用参数
}));
assert_eq!(log, ["你好", "再见"]);
}区别在于:异步闭包返回的 Future 被允许向闭包本身借东西(RFC 3668 称之为 lending,“出借”),.await 结束就归还,所以下一次调用又可以再借。这是 Fn() -> Fut 这种写法在类型上表达不出来的。
|| async { … } | async || { … } | |
|---|---|---|
| 是什么 | 普通闭包,返回值恰好是个 async 块 | 一种专门的闭包 |
| 返回的 Future 能借用闭包捕获的变量吗 | 不能(只能 move 进去,或先克隆) | 能 |
| 能接收“带生命周期的引用参数”并在 Future 里使用吗 | 很难写对 | 能 |
| 用什么约束来接收 | F: Fn() -> Fut, Fut: Future | F: AsyncFn() |
| 稳定版本 | 1.39 | 1.85 |
25.7.4 只能用一次的:AsyncFnOnce
如果闭包会把捕获的东西交出去,它就只能被调用一次:
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
}
}
async fn open_gift(gift: impl AsyncFnOnce() -> String) -> String {
gift().await // 只能调用这一次
}
fn main() {
let toy = String::from("小火车");
// async move:把 toy 搬进闭包;闭包体又把它交了出去
let gift = async move || toy;
assert_eq!(block_on(open_gift(gift)), "小火车");
}25.7.5 两个限制:不能 dyn,说不出 Send
限制一:AsyncFn* 不能做成 trait 对象。
fn main() {
// 错误:AsyncFn 不是 dyn 兼容的
let f: Box<dyn AsyncFn(i32) -> i32> = Box::new(async |x| x + 1);
}预期报错:error[E0038]: the trait `AsyncFn` is not dyn compatible。原因是每个异步闭包返回的 Future 类型都不同,而且这个类型还带着“借多久”的生命周期,没法放进一张固定的虚函数表。需要把“异步回调”存进 Box 或集合时,仍然用老办法——让普通闭包返回一个装箱的 Future:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
// 一个可以放进 Vec 的“异步回调”类型
type Callback = Box<dyn Fn(i32) -> Pin<Box<dyn Future<Output = i32>>>>;
fn main() {
let callbacks: Vec<Callback> = vec![
Box::new(|x| Box::pin(async move { x + 1 })),
Box::new(|x| Box::pin(async move { x * 2 })),
];
let mut cx = Context::from_waker(Waker::noop());
let mut results = Vec::new();
for callback in &callbacks {
let mut future = callback(10);
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
results.push(value);
}
}
assert_eq!(results, [11, 20]);
}限制二:没法要求“返回的 Future 是 Send”。
多线程运行时(例如 Tokio 默认的多线程调度器)的 spawn 要求任务是 Send,因为任务可能被换到另一个线程继续执行。AsyncFn 约束里只能写出参数和最终结果的类型,写不出那个中间的 Future 类型,也就没法给它加 Send:
// 模拟多线程运行时的 spawn:要求 Future 是 Send
fn spawn_like<F: Future + Send + 'static>(_future: F) {}
fn run<F>(f: F)
where
F: AsyncFn() + Send + 'static, // 这里的 Send 只约束了闭包本身
{
spawn_like(async move { f().await; }); // 错误:f() 返回的 Future 不一定是 Send
}
fn main() {}预期报错:error: future cannot be sent between threads safely。在这种公开的、需要跨线程的接口里,目前仍应使用两个类型参数的旧写法,这样可以直接给 Fut 加上 Send:
// 模拟多线程运行时的 spawn:要求 Future 是 Send
fn spawn_like<F: Future + Send + 'static>(_future: F) {}
fn run<F, Fut>(f: F)
where
F: Fn() -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send, // 可以明确要求 Send
{
spawn_like(async move { f().await; });
}
fn main() {
run(|| async {});
}怎么选:
图的文字版:要存成 dyn 用“返回装箱 Future 的普通闭包”;要保证 Send 用 F: Fn() -> Fut, Fut: Future + Send;其余情况用 AsyncFn*。
不要混淆
AsyncFn*、异步闭包、Future 都属于语言和标准库。tokio::spawn、tokio::join!、异步定时器等属于第三方运行时,标准库里没有。为什么任务要 Send、什么类型是 Send,见第 28 章。
25.7.6 小结
async |x| { … }是异步闭包:调用得到Future,.await后得到结果;1.85 起稳定。- 接收方用
AsyncFn/AsyncFnMut/AsyncFnOnce,它们在 prelude 里;async fn和“返回 Future 的普通闭包”也满足这些约束。 - 相比
|| async { … },异步闭包返回的 Future 可以借用闭包捕获的变量和带生命周期的参数。 - 两个限制:
AsyncFn*不能dyn;无法约束返回的 Future 为Send。遇到这两种需求,继续用Fn() -> Fut的写法。